<template>
  <div class="app-container customer-div">
    <el-menu :default-active="listQuery.type" class="el-menu-demo" mode="horizontal" @select="handleSelect">
      <el-menu-item index="sale">我的</el-menu-item>
      <el-menu-item index="all" v-if="allSaleDeliverConfirm">全部</el-menu-item>
    </el-menu>
    <div style="margin-top: 40px">
      <!--搜索-->
      <el-form :inline="true" :model="listQuery" size="mini" label-width="100px">
        <el-form-item label="订单时间：">
          <el-date-picker
            v-model="listQuery.orderCreateDate"
            type="daterange"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="客户名称：">
              <el-select
                      clearable
                      v-model="listQuery.customerName"
                      filterable
                      remote
                      reserve-keyword
                      placeholder="请输入关键词"
                      :remote-method="remoteMethod1"
                      :loading="customerLoading">
                <el-option
                        v-for="item in customerList"
                        :key="item.customerId"
                        :label="item.customerName"
                        :value="item.customerName">
                </el-option>
              </el-select>
        </el-form-item>
        <el-form-item label="客户编号：">
          <el-input v-model="listQuery.customerNumber"></el-input>

        </el-form-item>
        <el-form-item label="业务员：" v-if="listQuery.type == 'all'">
          <el-select v-model="listQuery.userId" filterable placeholder="请选择" clearable>
            <el-option
              v-for="item in userOptionList"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="回传时间：" v-if="listQuery.type == 'all'">
          <el-date-picker
            v-model="listQuery.receivedTime"
            type="daterange"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="合同编号：">
          <el-input v-model="listQuery.orderSn" clearable></el-input>
        </el-form-item>

<!--        <el-form-item label="是否开票：" v-if="listQuery.type == 'all'">-->
<!--          <el-select v-model="listQuery.invoiceStateNew"  placeholder="请选择" clearable>-->
<!--            <el-option :key="1" label="是" :value="1"></el-option>-->
<!--            <el-option :key="2" label="否" :value="2"></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->

        <el-form-item label="排货时间：">
          <el-date-picker
            v-model="listQuery.deliverDate"
            type="daterange"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="事业部：" >
          <el-select v-model="listQuery.divsionDeptId" filterable placeholder="请选择" clearable multiple>
            <el-option :value="item.divsionDeptId" :label="item.divsionDeptName" v-for="item in divisionList" :key="item.divsionDeptId"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
                  @click="handleSearchList()"
                  type="primary">
            查询
          </el-button>
          <el-button
            @click=" showPopFn('','more')"
            type="primary">
            合并上传
          </el-button>
          <el-button
            :loading="btnLoadingprint"
                  @click="showPrintLetter('','more')"
                  type="primary">
            合并打印
          </el-button>
          <el-button
            v-if="listQuery.type == 'all'"
            :loading="btnloadingExcel"
            @click="downloadExcel()"
            type="primary">
            待上传统计导出
          </el-button>
        </el-form-item>
      </el-form>

      <el-radio-group size="small" v-model="listQuery.printStatus" @change="handleSearchList">
         <el-radio-button label="">全部</el-radio-button>
         <el-radio-button label="0">待打印</el-radio-button>
         <el-radio-button label="1">待上传</el-radio-button>
         <el-radio-button label="2">已上传</el-radio-button>
      </el-radio-group>
    </div>


    <!--数据列表-->
    <div class="table-container">
      <el-table
              ref="multipleTable"
              row-key="deliverId"
              @selection-change="handleSelectionChange"
              :header-cell-style="{'text-align':'center'}"
              v-loading="listLoading"
              :data="tableData"
              border
              style="width: 100%; margin-top: 20px">
        <el-table-column type="selection" :reserve-selection="true" width="60" align="center" :selectable="selectable"></el-table-column>
        <el-table-column
          class-name="cspantd"
                label="订单时间"
                min-width="120"
                align="center">
          <template slot-scope="scope">
            <div class="tdDiv" v-for="(item,index) in scope.row.list" :key="index" :style="{'border-bottom': index==scope.row.list.length-1 ? '0px solid #EBEEF5' : '1px solid #EBEEF5'}">{{item.orderDate }}</div>
          </template>
        </el-table-column>
        <el-table-column
          class-name="cspantd"
          label="订单号"
          min-width="150"
          align="center">
          <template slot-scope="scope">
            <div class="tdDiv" style="color:#409EFF;cursor: pointer" v-for="(item,index) in scope.row.list" :key="index" :style="{'border-bottom': index==scope.row.list.length-1 ? '0px solid #EBEEF5' : '1px solid #EBEEF5'}" @click="toOrderInfo(item.orderId)">{{item.orderSn }}</div>
          </template>
        </el-table-column>

        <el-table-column label="客户编号" min-width="200" align="center">
          <template slot-scope="scope">
            <div>
              {{scope.row.customerNumber}}
            </div>
            <!--是否有权限-->
            <div v-if="scope.row.isShowCustomerName">{{scope.row.customerName}}</div>
          </template>
        </el-table-column>

        <el-table-column label="合同公司" min-width="200" align="center">
          <template slot-scope="scope">
            {{scope.row.companyName}}
          </template>
        </el-table-column>

        <el-table-column
                align="center"
                label="业务员"
                min-width="100">
          <template slot-scope="scope">
            {{scope.row.userName}}
          </template>
        </el-table-column>
        <el-table-column
          class-name="cspantd"
                align="center"
                label="商品名称"
                min-width="150">
          <template slot-scope="scope">
            <div  class="tdDiv" v-for="(item,index) in scope.row.list" :key="index" :style="{'border-bottom': index==scope.row.list.length-1 ? '0px solid #EBEEF5' : '1px solid #EBEEF5'}">{{item.goodsName }}{{item.goodsSn}}</div>
          </template>
        </el-table-column>
        <el-table-column
                label="合同数量"
                min-width="100"
                align="center">
          <template slot-scope="scope">
            {{scope.row.list | sumNum}}
          </template>
        </el-table-column>
        <el-table-column
                class-name="cspantd"
                align="center"
                label="排货数量"
                min-width="100">
          <template slot-scope="scope">
            <div class="tdDiv" v-for="(item,index) in scope.row.list" :key="index" :style="{'border-bottom': index==scope.row.list.length-1 ? '0px solid #EBEEF5' : '1px solid #EBEEF5'}">{{item.planNum}}</div>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="排货时间"
          min-width="100">
          <template slot-scope="scope">
              {{scope.row.shipTime}}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="回传时间"
          min-width="150">
          <template slot-scope="scope">
            {{scope.row.receivedTime}}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="回传人"
          min-width="100">
          <template slot-scope="scope">
            {{scope.row.receivedName}}
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          align="center"
          label="状态"
          min-width="100">
          <template slot-scope="scope">
              {{scope.row.printStatus | fifprintStatus }}
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          label="发货单号"
          min-width="100">
          <template slot-scope="scope">
            {{scope.row.deliverSn}}
          </template>
        </el-table-column>


        <el-table-column
          align="center"
          label="发票号"
          min-width="100">
          <template slot-scope="scope">
            {{scope.row.invoiceNo}}
          </template>
        </el-table-column>

        <el-table-column
          fixed="right"
          show-overflow-tooltip
          align="center"
          label="回单"
          min-width="100">
          <template slot-scope="scope">
            <div @click="fullImg(item)" style="color:#409EFF;cursor: pointer" v-for="(item,index) in scope.row.receivedPicUrl" :key="index">查看附件</div>
          </template>
        </el-table-column>

        <el-table-column
                fixed="right"
                min-width="160"
                align="center"
                label="操作">
          <template slot-scope="scope">
            <el-button
                    type="text"
                    size="mini"
                    @click="showPrintLetter(scope.row,'one')">打印
            </el-button>
            <el-button
                    type="text"
                    size="mini"
                    @click="showPopFn(scope.row,'one')">上传回单
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination-container">
      <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              layout="total, sizes,prev, pager, next,jumper"
              :current-page.sync="listQuery.pageNum"
              :page-size="listQuery.pageSize"
              :page-sizes="[10,15,20]"
              :total="count">
      </el-pagination>
    </div>

    <el-dialog
            title="上传回单"
            :visible.sync="showPop"
            width="600px">
      <el-form>
        <el-form-item label="上传回单：">
          <el-upload
                  drag
                  :data="uploadToken"
                  action="https://upload.qiniup.com"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
          <div>
            <div v-if="cutImg != ''">{{cutImg}}</div>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleConfirm" :loading="btnLoading2">确 定</el-button>
      </span>
    </el-dialog>

    <!--打印--->
    <printLetterNew ref="printLetterNew" @confirmPrint="confirmPrint"></printLetterNew>

    <!--放大图片-->
    <el-dialog
            :visible.sync="dialogVisible5"
            width="800">
      <img :src="fullSrc" style="width:100%"/>
    </el-dialog>

  </div>
</template>
<script>
import { getCustomerOption, getQiniuToken, getOrderUsersList } from '@/api/partner';
import { divisionDeptList } from '@/api/company';
import { printDeliverList, batchReceived ,unUploadSummary} from '@/api/plan';

import { formatDate } from '@/utils/date';
import store from '@/store';
import { mapGetters } from 'vuex';
import printLetterNew from './components/printLetterNew2';
  const defaultListQuery={
    pageNum: 1,
    pageSize: 10,
    customerName:'',
    type:'sale',
    printStatus:'',
    orderCreateDate:[],
    receivedTime:[],
    orderSn:'',
    invoiceStateNew:'',
    deliverDate:[],
    customerNumber:'',
    divsionDeptId:[],//事业部搜索
  };
  export default {
    name: "confirmationLetter",
    data(){
      return {
        listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
        tableData: [],
        count:0,
        listLoading: false,
        roles:store.getters.roles ? store.getters.roles : [],
        btnloading:false,
        customerLoading:false,
        customerList:[],
        showPop:false,
        btnLoading2:false,
        cutImg:'',
        uploadToken:{
          token:'',
        },
        imgDomain:'',
        dialogVisible5:false,
        fullSrc:'',
        selectList:[],
        cutReceivedIds:[],
        userOptionList:[],
        btnloadingExcel: false,
        divisionList:[],
        btnLoadingprint:false
      }
    },
    computed: {
      ...mapGetters([
        'name',
        'mobile',
        'userId',
        'isMange',
      ]),
      allSaleDeliverConfirm(){
        if(this.roles.indexOf("allSaleDeliverConfirm") != -1){
          return true
        }else{
          return false
        }
      },
    },
    components:{printLetterNew},
    created() {
      let now = new Date();
      let nowMonth = now.getMonth(); //当前月
      let nowYear = now.getFullYear(); //当前年
      //本月的开始时间
      let monthStartDate = new Date(nowYear, nowMonth, 1);
      //本月的结束时间
      let monthEndDate = new Date(nowYear, nowMonth+1, 0,23,59,59);
      let startDate = formatDate(monthStartDate, 'yyyy-MM-dd');
      let endDate = formatDate(monthEndDate, 'yyyy-MM-dd');
      this.listQuery.deliverDate = [startDate,endDate];

      if(this.$route.query.dataTab){
        this.listQuery.type = this.$route.query.dataTab == 'my' ? 'sale' : 'all'
      }
      if(this.$route.query.dataDate){
        this.listQuery.deliverDate = this.$route.query.dataDate;
      }
      if(this.$route.query.dataPrintStatus){
        this.listQuery.printStatus = this.$route.query.dataPrintStatus;
      }
      if(this.$route.query.type){
        this.listQuery.type = this.$route.query.type
      }
      if(this.$route.query.deliverDate){
        this.listQuery.deliverDate = this.$route.query.deliverDate.split(",")
      }
      if(this.$route.query.printStatus){
        this.listQuery.printStatus = this.$route.query.printStatus
      }
      this.getList();
      this.getUploadToken();
      this.getUserOptionList();
      this.getDivisionDeptList();
    },
    filters: {
      fifprintStatus(val){
        if(val === 0){
          return '待打印'
        }else if(val === 1){
          return '待上传'
        }else if(val === 2){
          return '已上传'
        }
      },
      sumNum(list){
        let sum = 0
        list.forEach((el)=>{
          sum = sum+parseFloat(el.goodsNum)
        })
        return sum.toFixed(4)
      },
    },
  methods: {
      //获取事业部列表
      getDivisionDeptList(){
        divisionDeptList().then((res)=>{
          this.divisionList = res
        })
      },
      //下载excle
      downloadExcel(){
        let params = JSON.parse(JSON.stringify(this.listQuery));

        this.btnloadingExcel = true;
        unUploadSummary(params).then((res)=>{
          this.btnloadingExcel = false;
          require.ensure([], () => {
            const { export_json_to_excel } = require('sheet/Export2Excel');
            const tHeader = res.title;
            const filterVal = res.columns;
            const list = res.list;
            const data = this.formatJson(filterVal, list);
            export_json_to_excel(tHeader, data, res.fileName);
          })
        }).catch(()=>{
          this.btnloadingExcel = false;
        })
      },

      //下载表格数据格式化
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]))
      },
      toOrderInfo(orderId){
        let routeData = this.$router.resolve({name:'saleDetail',query:{id:orderId,type:'see'}});
        window.open(routeData.href);
      },
      //获取员工下拉选项
      getUserOptionList(){
        getOrderUsersList().then((res)=>{
          this.userOptionList = res;
        })
      },
      selectable(row, index){
        return row.printStatus === 0 || row.printStatus === 1
      },
      confirmPrint(){
        this.selectList = [];
        this.$refs.multipleTable.clearSelection();
        this.getList()
      },
      //切换选择记录
      handleSelectionChange(val){
        this.selectList = JSON.parse(JSON.stringify(val));
      },

      handleSelect(key){
         this.listQuery = JSON.parse(JSON.stringify(defaultListQuery));
         this.listQuery.type = key;
          let now = new Date();
          let nowMonth = now.getMonth(); //当前月
          let nowYear = now.getFullYear(); //当前年
          //本月的开始时间
          let monthStartDate = new Date(nowYear, nowMonth, 1);
          //本月的结束时间
          let monthEndDate = new Date(nowYear, nowMonth+1, 0,23,59,59);
          let startDate = formatDate(monthStartDate, 'yyyy-MM-dd');
          let endDate = formatDate(monthEndDate, 'yyyy-MM-dd');
          this.listQuery.deliverDate = [startDate,endDate];
         this.handleSearchList()
      },
        //放大图片
        fullImg(item){
           window.open(item)
        },
        //上传图片
        handleAvatarSuccess(res){
            this.cutImg = this.imgDomain+res.key
        },
        //获取七牛TOKEN
        getUploadToken(){
            getQiniuToken().then((res)=>{
                this.uploadToken.token = res.token;
                this.imgDomain = res.domain
            })
        },
        handleClose(){
            this.showPop = false;
        },
        handleConfirm(){
            this.btnLoading2 = true;
            batchReceived({ids:this.cutReceivedIds.join(","),receivedUrl:this.cutImg}).then(()=>{
                this.btnLoading2 = false;
                this.handleClose();
                this.selectList = [];
                this.$refs.multipleTable.clearSelection();
                this.getList();
            }).catch(()=>{
                this.btnLoading2 = false;
            })
        },

        //显示上传弹窗
        showPopFn(item,type){
            if(type == 'more' && this.selectList.length == 0){
              this.$message({
                type: 'info',
                message: '请先选择记录！'
              });
              return false
            }
            this.showPop = true;
            this.cutImg = '';
            this.cutReceivedIds = [];
            if(type == 'more'){
              this.selectList.forEach((el)=>{
                this.cutReceivedIds.push(el.id)
              })
            }else{
              this.cutReceivedIds.push(item.id)
            }

        },

        //批量打印
       showPrintLetter(item,type){
          let ids = [];
           if(type == 'more' && this.selectList.length == 0){
             this.$message({
               type: 'info',
               message: '请先选择记录！'
             });
             return false
           }
           if(type == 'more'){
             this.selectList.forEach((el)=>{
               ids.push(el.id)
             })
           }else{
             ids.push(item.id)
           }
           this.$refs.printLetterNew.showPop(ids.join(","))
        },

        //获取客户列表
        remoteMethod1(query) {
            if(query && query!= ''){
                this.customerLoading = true;
                getCustomerOption({keywords:query}).then(response => {
                    this.customerList = response;
                    this.customerLoading = false;
                }).catch(()=>{
                    this.customerLoading = false;
                });
            }
        },



      handleSearchList(){
        this.listQuery.pageNum = 1;
        this.getList();
      },

        handleSizeChange(val){
            this.listQuery.pageNum = 1;
            this.listQuery.pageSize = val;
            this.getList();
        },
        handleCurrentChange(val){
            this.listQuery.pageNum = val;
            this.getList();
        },

      //获取列表
      getList() {
        this.listLoading = true;
        printDeliverList(this.listQuery).then(response => {
          this.tableData = response.list;
          this.count = response.count;
          this.listLoading = false;
        }).catch(()=>{
          this.listLoading = false;
        });
      },
    },
  }
</script>

<style scoped lang="scss">
.cspantd{
  padding:0 !important;
  .cell{
    padding:0 !important;
    .tdDiv{
      padding:5px 10px;
      min-height: 20px;
      line-height: 20px;
      box-sizing: content-box;
    }
  }
}
</style>
